package com.fmi.timedealer.achievement;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.fmi.timedealer.ActivityItem;
import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class ManageLevelItemActivity extends Activity {
	
	private AchievementLevelItem currentLevelItem = null;
	private int levelId;
	private IDataManager dbManager = null;
	private String selectedCategory = "";
	private ActivityItem selectedItem = null;
	private boolean updateAction = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.manage_level_items);
		dbManager = new SQLiteDataManager("MyDB", this);
		
		Bundle extras = getIntent().getExtras();
		currentLevelItem = (AchievementLevelItem)extras.getSerializable(AchievementsActivity.LEVEL_ITEM_BUNDLE_KEY);
		levelId = extras.getInt(AchievementsActivity.LEVEL_ID_BUNDLE_KEY);
		initCategorySpinner();
		fillViewsData(currentLevelItem);
		
		Button btnSave = (Button)findViewById(R.id.btn_save_level_item);
		btnSave.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				updateCurrentLevelItemValues();
				if (currentLevelItem.getId() == 0) {
					dbManager.insertLevelItem(currentLevelItem, levelId);
				}
				else {
					dbManager.updateLevelItem(currentLevelItem);
				}
				returnResult(Activity.RESULT_OK);
			}
		});
		
		Button btnCancel = (Button)findViewById(R.id.btn_cancel_level_item);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				returnResult(Activity.RESULT_CANCELED);
			}
		});
	}
	
	private void initCategorySpinner() {
		
		List<String> categories = Arrays.asList(dbManager.getCategoriesNames());
		Collections.sort(categories);
		Spinner spinner = (Spinner) findViewById(R.id.item_categories_snipper);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
        		android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnCategoryItemSelectedListener());
        if (currentLevelItem.getId() != 0) {
        	initActionSpinner(dbManager.getAllActivities(), "");
        }
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initActionSpinner(List<ActivityItem> activityItems, String category) {
		
		List<ActivityItem> filteredItems = filterItems(activityItems, category);
		Collections.sort(filteredItems);
		Spinner actionSpinner = (Spinner) findViewById(R.id.item_names_snipper);
		ArrayAdapter actionAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, filteredItems);
		actionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		actionSpinner.setAdapter(actionAdapter);
		actionSpinner.setClickable(true);
		actionSpinner.setOnItemSelectedListener(new OnActionItemSelectedListener());
	}
	
	private List<ActivityItem> filterItems(List<ActivityItem> activityItems, String category) {

		List<ActivityItem> filtered = new ArrayList<ActivityItem>();
		filtered.add(new ActivityItem("", "", ""));
		for (ActivityItem item : activityItems) {
			if (category.equals("") || category.equals(item.getCategory())) {
				filtered.add(item);
			}
		}
		return filtered;
	}
	
	private void updateCurrentLevelItemValues() {
			
			// Fill Goal data
			TextView tvGoal = (TextView)findViewById(R.id.text_goal);
			if (tvGoal != null) {
				currentLevelItem.setGoalTrackTime(Integer.parseInt(tvGoal.getText().toString()));
			}
			if (selectedItem != null) {
				currentLevelItem.setActivityItem(selectedItem);
			}
			
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void fillViewsData(AchievementLevelItem levelItem) {
		
		// Fill Goal data
		TextView tvGoal = (TextView)findViewById(R.id.text_goal);
		if (tvGoal != null) {
			tvGoal.setText(Integer.toString(levelItem.getGoalTrackTime()));
		}
		
		if (currentLevelItem.getId() != 0) {
			ActivityItem item = currentLevelItem.getActivityItem();
			
			Spinner categorySpinner = (Spinner) findViewById(R.id.item_categories_snipper);
			ArrayAdapter categoryAdapter = (ArrayAdapter) categorySpinner.getAdapter();
			int categoryPos = categoryAdapter.getPosition(item.getCategory());
			categorySpinner.setSelection(categoryPos);
			categorySpinner.setEnabled(false);
			
			Spinner actionSpinner = (Spinner) findViewById(R.id.item_names_snipper);
			ArrayAdapter actionAdapter = (ArrayAdapter) actionSpinner.getAdapter();
			int actionPos = -1;
			for (int i = 0; i < actionAdapter.getCount(); i++) {
				ActivityItem currItem = (ActivityItem) actionAdapter.getItem(i);
				if (item.getId() == currItem.getId()) {
					actionPos = i;
					break;
				}
			}
			actionSpinner.setSelection(actionPos);
			actionSpinner.setEnabled(false);
			
			updateAction = false;
		}
	}
	
	private void returnResult(int resultCode) {

		if (resultCode == RESULT_OK) {
			getIntent().removeExtra(AchievementsActivity.LEVEL_ITEM_BUNDLE_KEY);
			getIntent().putExtra(AchievementsActivity.LEVEL_ITEM_BUNDLE_KEY, currentLevelItem);
		}
		this.setResult(resultCode, getIntent());
		this.finish();
	}
	
	/**
	 * Custom onItemSelectedListener that handles the selection of items
	 * in the category name spinner. Takes care of knowing which category name is selected
	 * and updating the action name spinner with the correct actions
	 */
    public class OnCategoryItemSelectedListener implements OnItemSelectedListener {    

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {  
			selectedCategory = parent.getItemAtPosition(pos).toString();
			//TODO make the search criteria search by category instead of getting all items
			if (selectedCategory != "" && updateAction) {
				List<ActivityItem> activityItems = dbManager.getAllActivities();
				initActionSpinner(activityItems, selectedCategory);
			}
			updateAction = true;
		}   
		
		public void onNothingSelected(AdapterView<?> parent) {    
			// Do nothing.    
		}
	}
    
    /**
	 * Custom onItemSelectedListener that handles the selection of items
	 * in the action name spinner.
	 */
    public class OnActionItemSelectedListener implements OnItemSelectedListener {    

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {  
			selectedItem = (ActivityItem)parent.getItemAtPosition(pos);
		}   
		
		public void onNothingSelected(AdapterView<?> parent) {    
			// Do nothing.    
		}
	}
}
